package motionsApp.client;

import java.util.ArrayList;
import java.util.List;
import motionsApp.client.labeling.MotionLabeler;
import motionsApp.client.randomization.MotionRandomizer;
import motionsApp.shared.FieldVerifier;
import motionsApp.shared.MotionDTO;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

public class MotionsApp implements EntryPoint {
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	private final MotionsServiceAsync motionsService = GWT.create(MotionsService.class);

	public void onModuleLoad() {		
		final Button addMotionButton = new Button("Add");
		final TextArea motionTextBox = new TextArea();		
		final Label errorLabel = new Label();
		//sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		
		MotionsRepository motionsRepository = new MotionsRepository(motionsService);
		
		DisclosurePanel randomMotionPanel = new DisclosurePanel("Random motion");
		RootPanel.get().add(randomMotionPanel);		
		new MotionRandomizer(motionsRepository, randomMotionPanel);
		
		DisclosurePanel labelMotionPanel = new DisclosurePanel("Label a motion (or few)");
		RootPanel.get().add(labelMotionPanel);
		new MotionLabeler(motionsRepository, labelMotionPanel);
		
		RootPanel.get("newMotionContainer").add(motionTextBox);
		RootPanel.get("sendButtonContainer").add(addMotionButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);
		ReplaceTable("newMotionTable", "Add new motion");
		
		final RootPanel motionsContainer = RootPanel.get("motionsCell");
		ReplaceTable("motionsBrowserTable", "Browse all motions");
		
		
		refreshMotions(motionsContainer);
		
				// Focus the cursor on the name field when the app loads
		motionTextBox.setFocus(true);
		motionTextBox.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Motion added");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");		
		dialogVPanel.add(textToServerLabel);		
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				addMotionButton.setEnabled(true);
				addMotionButton.setFocus(true);
			}
		});
		
				// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendMotionToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendMotionToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendMotionToServer() {
				// First, we validate the input.
				errorLabel.setText("");
				String motion = motionTextBox.getText();
				if (!FieldVerifier.isValidName(motion)) {
					errorLabel.setText("Please enter at least four characters");
					return;
				}

				// Then, we send the input to the server.
				addMotionButton.setEnabled(false);
				//textToServerLabel.setText(motion);
				//serverResponseLabel.setText("");
				String[] motionsStrings = motion.split("\n");
				ArrayList<MotionDTO> newMotions = new ArrayList<MotionDTO>();
				for(String motionString: motionsStrings) {
					newMotions.add(new MotionDTO(motionString, new ArrayList<String>()));
				}
				
				motionsService.addNewMotion(newMotions,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox
										.setText("Remote Procedure Call - Failure");
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Motion Added");
								serverResponseLabel
										.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(result);
								dialogBox.center();
								closeButton.setFocus(true);
								refreshMotions(motionsContainer);
							}
						});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		addMotionButton.addClickHandler(handler);
		motionTextBox.addKeyUpHandler(handler);
	}

	private void setRandomMotion(final Label randomMotionLabel) {
		motionsService.getRandomMotion(new AsyncCallback<MotionDTO>() {
			
			@Override
			public void onSuccess(MotionDTO result) {
				randomMotionLabel.setText(result.getName());
			}
			
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	private void refreshMotions(final RootPanel motionsContainer) {
		motionsService.getMotions(new AsyncCallback<List<MotionDTO>>() {
			
			@Override
			public void onSuccess(List<MotionDTO> result) {
				String body = new String();
				
				int index = 1;
				for (MotionDTO motion : result) {
					body += index + ". "+ motion.getName() + "<br/>";
					index++;
				}			
				
				motionsContainer.clear();
				motionsContainer.add(new HTML(body));
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	private void ReplaceTable(String tableName, String panelHeader) {
		RootPanel randomMotionTable = RootPanel.get(tableName);
		randomMotionTable.removeFromParent();
		DisclosurePanel randomMotionPanel = new DisclosurePanel(panelHeader);
		randomMotionPanel.add(randomMotionTable);
		RootPanel.get().add(randomMotionPanel);
	}	
}
